import { Component, input, Input, KeyCode, Node, Sprite, SpriteFrame, _decorator } from 'cc';
import { Conn } from '../conn/Conn';
const { ccclass, property } = _decorator;

@ccclass('UISprint')
export class UISprint extends Component {

    isSprint = false;
    ctrlSet = new Set();

    @property(SpriteFrame)
    imgNormal: SpriteFrame
    @property(SpriteFrame)
    imgActed: SpriteFrame

    start() {
        this.node.on(Node.EventType.TOUCH_START, () => {
            this.ctrlSet.add(1);
        }, this);
        this.node.on(Node.EventType.TOUCH_END, () => {
            this.ctrlSet.delete(1);
        }, this);
        input.on(Input.EventType.KEY_DOWN, e => {
            if (e.keyCode === KeyCode.SPACE) {
                this.ctrlSet.add(2);
            }
        }, this);
        input.on(Input.EventType.KEY_UP, e => {
            if (e.keyCode === KeyCode.SPACE) {
                this.ctrlSet.delete(2);
            }
        }, this);
    }

    update() {
        const isSprint = this.ctrlSet.size > 0;
        if (this.isSprint != isSprint) {
            this.isSprint = isSprint;
            this.getComponent(Sprite).spriteFrame = isSprint ? this.imgActed : this.imgNormal;
            Conn.send(KProtoId.ctrlSprint, { isSprint });
        }
    }
}
